//
//  XMeViewController.m
//  ReceiveVouchers
//
//  Created by admin on 2017/7/5.
//  Copyright © 2017年 ReceiveVouchers. All rights reserved.
//

#import "XMeViewController.h"
#import "XPersonalDataViewController.h"
#import "KABadgeViewController.h"
#import "KAAboutViewController.h"

#import "AppDelegate.h"
#import "XMeCell.h"
#import "XMeHeaderView.h"
#import "NSString+Tools.h"
#import "UIImage+VR.h"
#import "KAUserinfoModel.h"
#import "NSDate+VR.h"
#import <AVFoundation/AVFoundation.h>
#import "VRView.h"

#pragma mark - const
//FOUNDATION_EXPORT NSString * const LQLoginSceneSBID;


//NSString * const LQLoginSceneSBID = @"LoginSceneSBID";

#define NewFucKey @"NewFucKey"


@interface XMeViewController ()

@property (nonatomic, strong)  XMeHeaderView *headerView;
@property (nonatomic, strong) KAUserinfoModel *userinfoModel;

@end

@implementation XMeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = nil;
    
    [self setupNav];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    [self setupSection0];
    [self setupSection1];
    [self setupSection2];
    [self setupHeaderView];
    
//    [self getUserinfo];
    
    [self test];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self getUserinfo];
}

- (void)setupNav
{
    
//    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    backBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
//    [backBtn setTitle:@"首页" forState:UIControlStateNormal];
//    backBtn.titleLabel.font = VRFont(14);
//    // 换肤
//    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    backBtn.imageEdgeInsets = UIEdgeInsetsMake(8, 15, 8, 0);
//    backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15 + 8, 0, 0);
//    [backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:backBtn];
//    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(0);
//        make.top.mas_equalTo(STATUS_BAR_HEIGHT);
//        make.width.mas_equalTo(70);
//        make.height.mas_equalTo(44);
//    }];
}

- (void)test
{
    VRView *testView = [[VRView alloc] init];
    testView.tag = 10001;
    testView.backgroundColor = RGBA(255, 0, 0, 0.5);
    testView.frame = CGRectMake(100, 100, 100, 100);
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture)];
    [testView addGestureRecognizer:tapGesture];
    [self.view addSubview:testView];
}

- (void)handleGesture
{
    NSLog(@"%s", __FUNCTION__);
}


- (void)setupSection0
{

    WeakSelf(weakSelf)
    XSettingItemModel *item0 = [XSettingItemModel itemWithIcon:@"me_badge" name:@"徽章"];
    item0.destVcClass = [KABadgeViewController class];
    item0.executeOperation = ^(NSIndexPath *indexPath) {
        
    };

    XSettingSectionModel *section0 = [[XSettingSectionModel alloc] init];
    section0.itemArray = [@[item0] mutableCopy];
    
    [self.sectionArray addObject:section0];
}

- (void)setupSection1
{
    
    WeakSelf(weakSelf)
    XSettingItemModel *item0 = [XSettingItemModel itemWithIcon:@"me_category" name:@"类别设置"];
    item0.executeOperation = ^(NSIndexPath *indexPath) {

    };
    
    XSettingItemModel *item1 = [XSettingItemModel itemWithIcon:@"me_alarm" name:@"定时提醒"];
    item1.executeOperation = ^(NSIndexPath *indexPath) {
        
    };
    
    XSettingItemModel *item2 = [XSettingItemModel itemWithIcon:@"me_sound" name:@"声音开关"];
    item2.isHaveSwitch = YES;
    item2.isOn = ![[NSUserDefaults standardUserDefaults] boolForKey:kVoiceSwitchIsCloseKey];
    item2.executeOperation = ^(NSIndexPath *indexPath) {
        
    };
    
    XSettingItemModel *item3 = [XSettingItemModel itemWithIcon:@"me_detail" name:@"明细详情"];
    item3.isHaveSwitch = YES;
    item3.isOn = ![[NSUserDefaults standardUserDefaults] boolForKey:kShowDetailSwitchIsCloseKey];
    item3.executeOperation = ^(NSIndexPath *indexPath) {
        
    };
    
    XSettingSectionModel *section1 = [[XSettingSectionModel alloc]init];
    section1.itemArray = [@[item2, item3] mutableCopy];
    
    [self.sectionArray addObject:section1];
}

- (void)setupSection2
{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    XSettingItemModel *item0 = [XSettingItemModel itemWithIcon:@"me_logo" name:[NSString stringWithFormat:@"关于%@", app_Name]];
    item0.destVcClass = [KAAboutViewController class];
    
    XSettingSectionModel *section2 = [[XSettingSectionModel alloc]init];
    section2.itemArray = [@[item0] mutableCopy];
    
    [self.sectionArray addObject:section2];
}


- (void)setupHeaderView
{
    
    
    CGFloat headerViewH = 216 + STATUS_BAR_HEIGHT - 20;
    
    self.headerView = [[XMeHeaderView alloc] init];
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, headerViewH);
    self.tableView.tableHeaderView = self.headerView;
    
    WeakSelf(weakSelf)
    self.headerView.CardPackageActionOperation = ^(NSInteger index) {
        
    };
    
    self.headerView.HeaderActionOperation = ^() {
        
        XPersonalDataViewController *personDataVc = [[XPersonalDataViewController alloc] init];
        personDataVc.userinfoModel = weakSelf.userinfoModel;
        [weakSelf.navigationController pushViewController:personDataVc animated:YES];
    };
    
    self.headerView.clockBlock = ^{
      
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSString *todayStr = [formatter stringFromDate:[NSDate date]];
        
        NSInteger clockCount = 1;
        if (weakSelf.userinfoModel.lastClockDate.length > 0) {
            
            NSDate *lastDate = [formatter dateFromString:weakSelf.userinfoModel.lastClockDate];
            
            NSDate *todayDate = [formatter dateFromString:todayStr];
            NSInteger lastDateTimeStamp = [todayDate timeIntervalSinceDate:lastDate];
            if (lastDateTimeStamp == 24 * 60 * 60) {
                clockCount += weakSelf.userinfoModel.clockCount;
            }
            
        }
        
        weakSelf.userinfoModel.clockCount = clockCount;
        weakSelf.userinfoModel.lastClockDate = todayStr;
        [[KADataBase sharedDataBase] updateUserinfo:weakSelf.userinfoModel];
        
        weakSelf.headerView.userinfoModel = weakSelf.userinfoModel;
        
        // 更新徽章表
        [[KADataBase sharedDataBase] updateBadgeWithType:1];
    };
}


- (void)clearUserInfo
{
    
    self.headerView.userinfoModel = nil;
}

#pragma mark - getData
- (void)getUserinfo
{
    self.userinfoModel = [[KADataBase sharedDataBase] getUserinfo];
    
    self.headerView.userinfoModel = self.userinfoModel;
}


#pragma mark - action
- (void)backAction:(UIButton *)sender
{
    
}


- (void)clearCache
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    
    for (NSString *p in files) {
        
        NSLog(@"file:%@", p);
        
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            //清理缓存，保留Preference，里面含有NSUserDefaults保存的信息
            if (![Path containsString:@"Preferences"]) {
                [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
            }
        }else{
            
        }
    }
}


- (void)switchClick:(BOOL)isOn indexPath:(NSIndexPath *)indexPath
{
    
    // 取出数据模型
    XSettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    XSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    itemModel.isOn = isOn;
    if (indexPath.section == 1 && indexPath.row == 0) { // 声音开关
        
        [[NSUserDefaults standardUserDefaults] setBool:!isOn forKey:kVoiceSwitchIsCloseKey];
        if (isOn) {
//            NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"push" ofType:@"mp3"];
//            NSURL *url = [NSURL fileURLWithPath:urlPath];
//            SystemSoundID ID;
//            AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &ID);
//            AudioServicesPlaySystemSound(ID);
//            AudioServicesAddSystemSoundCompletion(ID, NULL, NULL, &playFinished2, (__bridge void *)(self));
            
            AudioServicesPlaySystemSound(1007);
        }else{
            
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        }
    }else if (indexPath.section == 1 && indexPath.row == 1){    // 明细详情
        
        [[NSUserDefaults standardUserDefaults] setBool:!isOn forKey:kShowDetailSwitchIsCloseKey];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

void playFinished2(SystemSoundID ssID, void* clientData)
{
    unsigned long ID = ssID; // ssID 不能直接作为参数打印出来，需要中转一次
    AudioServicesDisposeSystemSoundID(ssID);
    AudioServicesRemoveSystemSoundCompletion(ssID);
}


#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 取出数据模型
    XSettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    XSettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    
    XMeCell *cell = [XMeCell cellWith:tableView];
    WeakSelf(weakSelf)
    cell.switchChangeOperation = ^(BOOL isOn) {
        [weakSelf switchClick:isOn indexPath:indexPath];
    };
    
    cell.model = itemModel;
    if (indexPath.row < sectionModel.itemArray.count - 1) {
        
        cell.lineType = LineTypeCenter;
    }else{
        
        cell.lineType = LineTypeTopAndBottom;
    }
    
    return cell;
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGPoint offset = scrollView.contentOffset;
    if (offset.y <= 0) {
        
        CGFloat scale = ABS(offset.y) / (174.5 * ScreenScale);

        CGFloat bgImageY = offset.y;
//        CGFloat bgImageW = (kScreenWidth + 0) * (1 + scale);
//        CGFloat bgImageH = (174.5 * kScreenRatio + 0) * (1 + scale);
//        self.headerView.bgImageView.frame = CGRectMake(0, bgImageY, bgImageW, bgImageH);
        self.headerView.bgImageView.frame = CGRectMake(0, bgImageY, kScreenWidth, 216 + STATUS_BAR_HEIGHT - 20 - offset.y);
        self.headerView.bgImageView.centerX = self.view.centerX;
    }
}


- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}


@end
